package dao;

import entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao extends BaseDao {

    /**
     * 验证用户登录
     * @param account 用户账号
     * @param password 用户密码
     * @return 验证成功返回 User 对象，否则返回 null
     */
    public User login(String account, String password) {
        String sql = "SELECT * FROM User WHERE account = ? AND password = ?";
        User user = null;
        Connection conn = getConnection();

        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, account);
            pstmt.setString(2, password);

            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    user = new User();
                    user.setId(rs.getInt("id"));
                    user.setAccount(rs.getString("account"));
                    user.setNickname(rs.getString("nickname"));
                    user.setPassword(rs.getString("password"));
                    user.setGender(rs.getByte("gender"));
                    user.setIdCard(rs.getString("idCard"));
                    user.setEmail(rs.getString("email"));
                    user.setPhone(rs.getString("phone"));
                    user.setType(rs.getByte("type"));
                    user.setOpenId(rs.getString("openId"));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, null, null);
        }

        return user;
    }

    /**
     * 注册新用户
     * @param user 待注册的用户对象
     * @return 注册成功返回 true，否则返回 false
     */
    public boolean register(User user) {
        String sql = "INSERT INTO User (account, password, nickname, gender, idCard, email, phone, type, openId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        Object[] params = {user.getAccount(), user.getPassword(), user.getNickname(), user.getGender(), user.getIdCard(), user.getEmail(), user.getPhone(), user.getType(), user.getOpenId()};
        int rowsAffected = exceuteUpdate(sql, params);

        return rowsAffected > 0;
    }
}
